// 文件系统API服务
// 提供文件和目录操作的API接口

import { apiClient, RequestConfig } from './ApiClient';

// 文件系统相关类型
export interface WorkspaceInfo {
  path: string;
  name: string;
  files: FileInfo[];
  totalFiles: number;
  totalSize: number;
  languages: LanguageStats[];
  lastModified: string;
}

export interface FileInfo {
  path: string;
  name: string;
  size: number;
  isDirectory: boolean;
  extension?: string;
  language?: string;
  lastModified: string;
  permissions: FilePermissions;
}

export interface FilePermissions {
  readable: boolean;
  writable: boolean;
  executable: boolean;
}

export interface LanguageStats {
  language: string;
  fileCount: number;
  totalLines: number;
  totalSize: number;
}

export interface FileOperationResult {
  success: boolean;
  path: string;
  operation: string;
  timestamp: string;
}

export interface DirectoryWatchResult {
  watcherId: string;
  path: string;
  isActive: boolean;
}

export interface FileChange {
  path: string;
  changeType: 'created' | 'modified' | 'deleted' | 'renamed';
  content?: string;
  timestamp: string;
  oldPath?: string; // for rename operations
}

// 文件系统API类
export class FileSystemApi {
  // 打开工作区
  async openWorkspace(
    path: string,
    config?: RequestConfig
  ): Promise<WorkspaceInfo> {
    return apiClient.invoke<WorkspaceInfo>(
      'open_workspace',
      { path },
      {
        ...config,
        cache: true,
        cacheKey: `workspace:${path}`,
        cacheTTL: 60000, // 1分钟缓存
      }
    );
  }

  // 读取文件内容
  async readFile(
    path: string,
    config?: RequestConfig
  ): Promise<string> {
    return apiClient.invoke<string>(
      'read_file',
      { path },
      {
        ...config,
        cache: true,
        cacheKey: `file:${path}`,
        cacheTTL: 30000, // 30秒缓存
      }
    );
  }

  // 写入文件内容
  async writeFile(
    path: string,
    content: string,
    config?: RequestConfig
  ): Promise<FileOperationResult> {
    // 清除相关缓存
    apiClient.clearCache(`file:${path}`);
    
    return apiClient.invoke<FileOperationResult>(
      'write_file',
      { path, content },
      config
    );
  }

  // 创建文件
  async createFile(
    path: string,
    content: string = '',
    config?: RequestConfig
  ): Promise<FileOperationResult> {
    return apiClient.invoke<FileOperationResult>(
      'create_file',
      { path, content },
      config
    );
  }

  // 创建目录
  async createDirectory(
    path: string,
    config?: RequestConfig
  ): Promise<FileOperationResult> {
    return apiClient.invoke<FileOperationResult>(
      'create_directory',
      { path },
      config
    );
  }

  // 删除文件或目录
  async deleteFileOrDirectory(
    path: string,
    config?: RequestConfig
  ): Promise<FileOperationResult> {
    // 清除相关缓存
    apiClient.clearCache(`file:${path}`);
    apiClient.clearCache(`directory:${path}`);
    
    return apiClient.invoke<FileOperationResult>(
      'delete_file_or_directory',
      { path },
      config
    );
  }

  // 重命名文件或目录
  async renameFileOrDirectory(
    oldPath: string,
    newPath: string,
    config?: RequestConfig
  ): Promise<FileOperationResult> {
    // 清除相关缓存
    apiClient.clearCache(`file:${oldPath}`);
    apiClient.clearCache(`file:${newPath}`);
    
    return apiClient.invoke<FileOperationResult>(
      'rename_file_or_directory',
      { oldPath, newPath },
      config
    );
  }

  // 读取目录内容
  async readDirectory(
    path: string,
    config?: RequestConfig
  ): Promise<FileInfo[]> {
    return apiClient.invoke<FileInfo[]>(
      'read_directory',
      { path },
      {
        ...config,
        cache: true,
        cacheKey: `directory:${path}`,
        cacheTTL: 30000, // 30秒缓存
      }
    );
  }

  // 监控目录变化
  async watchDirectory(
    path: string,
    config?: RequestConfig
  ): Promise<DirectoryWatchResult> {
    return apiClient.invoke<DirectoryWatchResult>(
      'watch_directory',
      { path },
      config
    );
  }

  // 停止监控目录
  async unwatchDirectory(
    watcherId: string,
    config?: RequestConfig
  ): Promise<boolean> {
    return apiClient.invoke<boolean>(
      'unwatch_directory',
      { watcherId },
      config
    );
  }

  // 获取文件统计信息
  async getFileStats(
    path: string,
    config?: RequestConfig
  ): Promise<FileInfo> {
    return apiClient.invoke<FileInfo>(
      'get_file_stats',
      { path },
      {
        ...config,
        cache: true,
        cacheKey: `stats:${path}`,
        cacheTTL: 60000, // 1分钟缓存
      }
    );
  }

  // 搜索文件
  async searchFiles(
    pattern: string,
    directory?: string,
    options?: {
      includeContent?: boolean;
      maxResults?: number;
      fileTypes?: string[];
    },
    config?: RequestConfig
  ): Promise<FileInfo[]> {
    return apiClient.invoke<FileInfo[]>(
      'search_files',
      { pattern, directory, options },
      config
    );
  }

  // 批量操作
  async batchOperations(
    operations: Array<{
      type: 'read' | 'write' | 'create' | 'delete' | 'rename';
      path: string;
      content?: string;
      newPath?: string;
    }>,
    config?: RequestConfig
  ): Promise<FileOperationResult[]> {
    return apiClient.invoke<FileOperationResult[]>(
      'batch_file_operations',
      { operations },
      config
    );
  }

  // 监听文件变化事件
  async onFileChange(
    callback: (change: FileChange) => void
  ): Promise<() => void> {
    return apiClient.listen<FileChange>('file-change', callback);
  }

  // 监听目录变化事件
  async onDirectoryChange(
    callback: (change: FileChange) => void
  ): Promise<() => void> {
    return apiClient.listen<FileChange>('directory-change', callback);
  }

  // 获取工作区语言统计
  async getLanguageStats(
    workspacePath: string,
    config?: RequestConfig
  ): Promise<LanguageStats[]> {
    return apiClient.invoke<LanguageStats[]>(
      'get_language_stats',
      { workspacePath },
      {
        ...config,
        cache: true,
        cacheKey: `lang-stats:${workspacePath}`,
        cacheTTL: 300000, // 5分钟缓存
      }
    );
  }

  // 验证文件路径
  async validatePath(
    path: string,
    config?: RequestConfig
  ): Promise<{
    isValid: boolean;
    exists: boolean;
    isAccessible: boolean;
    error?: string;
  }> {
    return apiClient.invoke(
      'validate_path',
      { path },
      config
    );
  }

  // 获取文件内容预览
  async getFilePreview(
    path: string,
    maxLines: number = 100,
    config?: RequestConfig
  ): Promise<{
    content: string;
    isTruncated: boolean;
    totalLines: number;
    encoding: string;
  }> {
    return apiClient.invoke(
      'get_file_preview',
      { path, maxLines },
      {
        ...config,
        cache: true,
        cacheKey: `preview:${path}:${maxLines}`,
        cacheTTL: 60000, // 1分钟缓存
      }
    );
  }
}

// 全局文件系统API实例
export const fileSystemApi = new FileSystemApi();

// 导出类型
export type {
  WorkspaceInfo,
  FileInfo,
  FilePermissions,
  LanguageStats,
  FileOperationResult,
  DirectoryWatchResult,
  FileChange,
};
